package com.linkage.jz.bankruptcy.activity.Project.ZQUser;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Main.CreateAddrActivity;
import com.linkage.jz.bankruptcy.activity.Main.TempleyActivity;
import com.linkage.jz.bankruptcy.activity.Project.EditOtherUserInfoActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.DetailOper.ChangerZQUserNameActivity;
import com.linkage.jz.bankruptcy.adapter.FullyGridLayoutManager;
import com.linkage.jz.bankruptcy.base.BaseCreateActivity;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.FileUtil;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.seapeak.base.BaseWhiteActivity;
import com.linkage.seapeak.base.BaseWhiteCreateActivity;
import com.linkage.seapeak.pojo.UploadImage;
import com.linkage.seapeak.utils.ToastUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.linkage.jz.bankruptcy.base.BaseCreateActivity.NAME_ADD;

public class AddProxyUserActivity extends BaseWhiteCreateActivity {

    private int REQUEST_CODE_ADDRESS = 10001;
    private String projectId;
    private String creditorId;

    // 代理人授权委托
    private RecyclerView recyclerImgsNumber;
    private List<UploadImage> imageListNumber = new ArrayList<>();
    private GridImagesAdapter imgAdapterNumber;

    private RecyclerView recyclerImgsWt;
    private List<UploadImage> imageListWt = new ArrayList<>();
    private GridImagesAdapter imgAdapterWt;

    private static final int TYPE_UPLOAD = 0; // 0:线上,1:线下
    private static final int TYPE_LOCAL = 1;

    private EditText proxyUserName;
    private EditText proxyUserPhone;
    private EditText proxyUserEmail;
    private EditText proxyUserOtherPhone;
    private EditText proxyRegisterNumber;
    private RadioGroup radioGroupNumber;
    private RadioGroup radioGroupWt;
    private TextView sendAddress;
    private TextView proxy_show_temp_xts;
    private static int mType; //0新增 1修改
    private static int mUserType;//0管理人 1 债权人

    PublicNoticeDialog noticeDialog;

    public static void start(Context context, String projectId, String creditorId, int type, int userType) {
        Intent intent = new Intent(context, AddProxyUserActivity.class);
        intent.putExtra("projectId", projectId);
        intent.putExtra("creditorId", creditorId);
        mType = type;
        mUserType = userType;
        context.startActivity(intent);

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (mType == 0) {
            setContentView(R.layout.activity_add_proxy_user, "新增代理人");
        } else {
            setContentView(R.layout.activity_add_proxy_user, "更改代理人");
        }
        initView();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_ADDRESS) {
//                address = (AddressInfo) data.getSerializableExtra("address");
//                tvAddr.setText(address.getDetailString());
                sendAddress.setTag(data.getStringExtra("id"));
                sendAddress.setText(data.getStringExtra("desc"));
            }
        }
    }

    @Override
    public void finish() {
        noticeDialog = new PublicNoticeDialog(AddProxyUserActivity.this, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.getId() == R.id.btn_save_notice) {
                    AddProxyUserActivity.super.finish();
                }
                noticeDialog.dismiss();
            }
        }, 1, "提示", "放弃编辑？",
                "否", "是");
        noticeDialog.show();
    }

    private void initView() {
        projectId = getIntent().getStringExtra("projectId");
        creditorId = getIntent().getStringExtra("creditorId");

        proxy_show_temp_xts = findViewById(R.id.proxy_show_temp_xts);
        proxy_show_temp_xts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TempleyActivity.start(AddProxyUserActivity.this,2);
            }
        });

        proxyUserName = (EditText) findViewById(R.id.proxy_user_name);
        proxyUserPhone = (EditText) findViewById(R.id.proxy_user_phone);
        proxyRegisterNumber = (EditText) findViewById(R.id.proxy_register_number);
        proxyUserOtherPhone = (EditText) findViewById(R.id.proxy_user_other_phone);
        proxyUserEmail = (EditText) findViewById(R.id.proxy_user_email);
        radioGroupNumber = (RadioGroup) findViewById(R.id.radio_group_number);
        recyclerImgsNumber = (RecyclerView) findViewById(R.id.recycler_imgs_number);
        radioGroupWt = (RadioGroup) findViewById(R.id.radio_group_wt);
        recyclerImgsWt = (RecyclerView) findViewById(R.id.recycler_imgs_wt);
        sendAddress = (TextView) findViewById(R.id.send_address);

        recyclerImgsNumber.setLayoutManager(new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL,
                false));
        imgAdapterNumber = new GridImagesAdapter(this, TYPE_EDIT);
        imgAdapterNumber.setList(imageListNumber);
        recyclerImgsNumber.setAdapter(imgAdapterNumber);

        recyclerImgsWt.setLayoutManager(new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL,
                false));
        imgAdapterWt = new GridImagesAdapter(this, TYPE_EDIT);
        imgAdapterWt.setList(imageListWt);
        recyclerImgsWt.setAdapter(imgAdapterWt);

        // 代理人身份证/执业证提供方式
        ((RadioGroup) findViewById(R.id.radio_group_number)).setOnCheckedChangeListener((radioGroup, which) -> {
            if (which == R.id.number_left) {
//                provideBusinessLicense = TYPE_UPLOAD;
                findViewById(R.id.recycler_imgs_number).setVisibility(View.VISIBLE);
            } else if (which == R.id.number_right) {
//                provideBusinessLicense = TYPE_LOCAL;
                findViewById(R.id.recycler_imgs_number).setVisibility(View.GONE);
            }
        });

        // 授权委托书提供方式
        ((RadioGroup) findViewById(R.id.radio_group_wt)).setOnCheckedChangeListener((radioGroup, which) -> {
            if (which == R.id.wt_left) {
//                provideBusinessLicense = TYPE_UPLOAD;
                findViewById(R.id.recycler_imgs_wt).setVisibility(View.VISIBLE);
            } else if (which == R.id.wt_right) {
//                provideBusinessLicense = TYPE_LOCAL;
                findViewById(R.id.recycler_imgs_wt).setVisibility(View.GONE);
            }
        });


        sendAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AddProxyUserActivity.this, CreateAddrActivity.class);
                intent.putExtra(CreateAddrActivity.KEY_FROM,CreateAddrActivity.FROM_FLOW);
                startActivityForResult(intent, REQUEST_CODE_ADDRESS);
            }
        });

        addMenu(new MenuAction(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveData();
            }
        }, "提交", 0));
    }

    /**
     * 保存信息
     */
    private void saveData() {
        if (TextUtils.isEmpty(proxyUserName.getText().toString())) {
            showToast("代理人姓名不可为空");
            return;
        }

        if (TextUtils.isEmpty(proxyUserPhone.getText().toString())) {
            showToast("代理人电话不可为空");
            return;
        }

        if (TextUtils.isEmpty(proxyRegisterNumber.getText().toString())) {
            showToast("代理人身份证/执业证号码不可为空");
            return;
        }

//        if(radioGroupNumber.getCheckedRadioButtonId() == R.id.number_left)
        int num = 0;
            for (UploadImage image : imageListNumber) {
                if (TextUtils.equals(image.getFilename(), NAME_ADD)) {
                    continue;
                }
                num ++;
            }

        if (num == 0 &&  radioGroupNumber.getCheckedRadioButtonId() == R.id.number_left) {
            showToast("代理人身份证/执业证图片不可为空");
            return;
        }

        num = 0;
        for (UploadImage image : imageListWt) {
            if (TextUtils.equals(image.getFilename(), NAME_ADD)) {
                continue;
            }
            num ++;
        }

        if (num == 0 &&  radioGroupWt.getCheckedRadioButtonId() == R.id.wt_left) {
            showToast("代理人授权委托书图片不可为空");
            return;
        }

        JSONArray fileArr = new JSONArray();


        for (int i = 0; i < imageListNumber.size(); i++) {
            if (TextUtils.equals(imageListNumber.get(i).getFilename(), NAME_ADD)) {
                continue;
            }
            JSONObject obj = new JSONObject();
            try {
                if (FileUtil.isImage(imageListNumber.get(i).getFilename())) {
                    obj.putOpt("attachmentName", "相关附件" + (i + 1) + ".jpg");
                } else {
                    obj.putOpt("attachmentName", imageListNumber.get(i).getFilename());
                }
                obj.putOpt("attachmentDownloadAddress", imageListNumber.get(i).getFilepath());
                obj.putOpt("attachmentSize", imageListNumber.get(i).getFilesize());
                obj.putOpt("loadUrl", imageListNumber.get(i).getLoadUrl());
                fileArr.put(obj);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


        JSONArray fileArr2 = new JSONArray();


        for (int i = 0; i < imageListWt.size(); i++) {
            if (TextUtils.equals(imageListWt.get(i).getFilename(), NAME_ADD)) {
                continue;
            }
            JSONObject obj = new JSONObject();
            try {
                if (FileUtil.isImage(imageListWt.get(i).getFilename())) {
                    obj.putOpt("attachmentName", "相关附件" + (i + 1) + ".jpg");
                } else {
                    obj.putOpt("attachmentName", imageListWt.get(i).getFilename());
                }
                obj.putOpt("attachmentDownloadAddress", imageListWt.get(i).getFilepath());
                obj.putOpt("attachmentSize", imageListWt.get(i).getFilesize());
                obj.putOpt("loadUrl", imageListWt.get(i).getLoadUrl());
                fileArr.put(obj);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if (mType == 0) {
            Network.getAPIService()
                    .addCreditorAgent(getUserToken(), creditorId, projectId,
                            proxyUserName.getText().toString(),
                            proxyUserPhone.getText().toString(),
                            proxyUserOtherPhone.getText().toString(),
                            proxyUserEmail.getText().toString(),
                            proxyRegisterNumber.getText().toString(),
                            radioGroupNumber.getCheckedRadioButtonId() == R.id.number_left ? 0 : 1,
                            fileArr.toString(),
                            radioGroupWt.getCheckedRadioButtonId() == R.id.wt_left ? 0 : 1,
                            fileArr2.toString(),
                            ((String) sendAddress.getTag()),
                            mUserType)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseSubscriber<JsonObject>() {
                        @Override
                        public void onNext(JsonObject json) {
                            int code = json.get("code").getAsInt();
                            if (code != 0) {
//                                showToast("设置失败");
//                                super.onNext(json);
                                String msg = ((JsonObject) json).get("msg").getAsString();
                                showToast(msg, com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
                                return;
                            } else {
//                                showToast("设置完成！", ToastUtil.TOAST_TYPE.SUCCESS);

                                if(mUserType== 1)
                                {
                                    noticeDialog = new PublicNoticeDialog(AddProxyUserActivity.this, new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            if (v.getId() == R.id.btn_save_notice) {
                                            }
                                            noticeDialog.dismiss();
                                            AddProxyUserActivity.super.finish();
                                        }
                                    }, 5, "提示", "新增代理人名称信息已经提交管理人审核，如有疑问，可于管理人联系。",
                                            "取消", "确认");
                                    noticeDialog.show();

                                }else {
                                    ToastUtil.getInstance(AddProxyUserActivity.this).showShortToast("新增代理人成功！");
                                    AddProxyUserActivity.super.finish();
                                }
                            }
                        }

                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {
                            showToast("新增失败");
                        }
                    });
        } else {
            Network.getAPIService()
                    .editCreditorAgent(getUserToken(), creditorId, projectId,
                            proxyUserName.getText().toString(),
                            proxyUserPhone.getText().toString(),
                            proxyUserOtherPhone.getText().toString(),
                            proxyUserEmail.getText().toString(),
                            proxyRegisterNumber.getText().toString(),
                            radioGroupNumber.getCheckedRadioButtonId() == R.id.number_left ? 0 : 1,
                            fileArr.toString(),
                            radioGroupWt.getCheckedRadioButtonId() == R.id.wt_left ? 0 : 1,
                            fileArr2.toString(),
                            ((String) sendAddress.getTag()),
                            mUserType
                    )
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseSubscriber<JsonObject>() {
                        @Override
                        public void onNext(JsonObject json) {
                            int code = json.get("code").getAsInt();
                            if (code != 0) {
//                                showToast("设置失败");
//                                super.onNext(json);
                                String msg = ((JsonObject) json).get("msg").getAsString();
                                showToast(msg, com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
                                return;
                            } else {
                                if(mUserType== 1)
                                {
                                    noticeDialog = new PublicNoticeDialog(AddProxyUserActivity.this, new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            if (v.getId() == R.id.btn_save_notice) {
                                            }
                                            noticeDialog.dismiss();
                                            AddProxyUserActivity.super.finish();
                                        }
                                    }, 5, "提示", "更改代理人名称信息已经提交管理人审核，如有疑问，可于管理人联系。",
                                            "取消", "确认");
                                    noticeDialog.show();

                                }else {
                                    ToastUtil.getInstance(AddProxyUserActivity.this).showShortToast("更改代理人成功！");
                                    AddProxyUserActivity.super.finish();
                                }
//                                showToast("设置完成！", ToastUtil.TOAST_TYPE.SUCCESS);
                            }
                        }

                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {
                            showToast("更改失败");
                        }
                    });
        }
    }
}
